import {Effect, ImmerReducer, Reducer, Subscription, history} from 'umi';

import {getItem, setItem, removeItem} from './storage';

import {getCaptcha, login, getUserInfo, logout, changePassword, getRoleId} from '@/services/login'
import {message} from "antd";

const Message = message

interface LoginState {
  title: string;
  authorization: string;
  sidebar: {
    collapse: string;
  };
  captcha: any;
  userInfo: any;
  roleId: any;
  device: string;
}

interface LoginModel {
  namespace: string;
  state: LoginState
  effects: {
    setCollapse: Effect;
    clearCollapse: Effect;
    setDevice: Effect;
    setToken: Effect;
    initToken: Effect;
    clearToken: Effect;
    setScreenCode: Effect;
    getCaptcha: Effect;
    login: Effect;
    getUserInfo: Effect;
    logout: Effect;
    changePassword: Effect;
    getRoleId: Effect;
    unLock: Effect;
  };
  reducers: {
    save: Reducer<LoginState>;
    setCaptcha: Reducer;
    setUserInfo: Reducer;
    setRoleId: Reducer;
  };
  subscription: {

  }
}

const LoginModel: LoginModel = {
  namespace: 'login',
  state: {
    title: '白兰培训管理系统',
    captcha: {codeKey: '1', codeValue: '1'},
    authorization: getItem('TOKEN') || '',
    sidebar: {
      collapse: getItem('COLLAPSE') || '',
    },
    userInfo: {},
    device: 'desktop',
    roleId: 0,
  },
  effects: {
    * setCollapse({payload}, {call, put}) {
      yield put({
        type: 'save',
        payload: {
          sidebar: {
            collapse: payload,
          },
        },
      });
      yield call(setItem, 'COLLAPSE', payload);
    },
    * clearCollapse(_, {call, put}) {
      yield put({
        type: 'save',
        payload: {
          sidebar: {
            collapse: '',
          },
        },
      });
      yield call(removeItem, 'COLLAPSE');
    },
    * setDevice({payload}, {put}) {
      yield put({
        type: 'save',
        payload: {
          device: payload,
        },
      });
    },
    * setToken({payload}, {call, put}) {
      yield put({
        type: 'save',
        payload: {
          authorization: payload,
        },
      });
      yield call(setItem, 'TOKEN', payload);
    },
    * initToken({payload}, {put, call}) {
      yield put({type: 'clearToken'});
      yield put({type: 'setToken', payload});
    },
    * clearToken(_, {call, put}) {
      yield put({type: 'setToken', payload: ''});
      yield call(removeItem, 'TOKEN');
      yield put({type: 'useAccount/clearUserinfo'});
      yield put({type: 'useTags/clearAllTags'});
      yield put({type: 'useMenus/setMenus', payload: []});
    },
    * setScreenCode({payload}, {put, call, select}) {
      const token = getItem("TOKEN")
      if(payload) {
        setItem("TOKEN", {...token, password: payload.password})
      }
    },
    * getCaptcha({payload}, {put, call}) {
      const {data} = yield call(getCaptcha)
      yield put({
        type: 'setCaptcha',
        payload: data,
      })
    },
    *login({payload}, {put, call}) {
      const {code, data, message} = yield call(login, payload)
      if(code === 200) {
        history.push('/home')
        Message.success("登录成功")
      } else {
        Message.error(message)
      }
      yield put({
        type: 'save',
        payload: {
          authorization: {
            ...payload,
            ...data,
          },
        },
      });
      yield call(setItem, 'TOKEN', data);
    },
    *getUserInfo({payload}, {put, call}) {
      const {data} = yield call(getUserInfo)
      yield put({
        type: 'setUserInfo',
        payload: data,
      })
    },
    *logout({payload}, {put, call}) {
      const {code} = yield call(logout)
      if(code === 200) {
        message.error("已退出登录，即将回到登录界面")
        removeItem("TOKEN")
        setTimeout(() => {
          history.push("/login")
        }, 1500)
      }
    },
    *changePassword({payload}, {call}) {
      const {code} = yield call(changePassword, payload)
      return code;
    },
    *getRoleId({payload}, {put, call}) {
      const {data} = yield call(getRoleId)
      yield put({
        type: 'setRoleId',
        payload: data,
      })
      return data
    },
    *unLock({payload}, {call}) {
      const TOKEN = getItem("TOKEN")
      if(!TOKEN.password){
        message.success("解锁成功")
        history.push("/main")
      }else if(payload !== TOKEN.password) {
        message.error("密码错误")
      } else {
        message.success("解锁成功")
        setItem("TOKEN", {token: TOKEN.token, refresh_token: TOKEN.refresh_token})
        history.push("/main")
      }
    }
  },
  reducers: {
    save(state, action) {
      return {...state, ...action.payload};
    },
    setCaptcha(state, {payload}) {
      return {
        ...state,
        captcha: payload,
      }
    },
    setUserInfo(state, {payload}) {
      return {
        ...state,
        userInfo: payload,
      }
    },
    setRoleId(state, {payload}) {
      return {
        ...state,
        roleId: payload,
      }
    },
  },
};

export default LoginModel;
